﻿using System;
using System.Web.UI;
using ITViet.Domains;
using ITViet.Services;
using ITViet.Web.App_Code;

namespace ITViet.Web.Admin
{
  public partial class Login : AdminBasePage
  {
    protected string url = "AccountInfo.aspx";

    protected void Page_Load(object sender, EventArgs e)
    {
      if (IsPostBack || IsCallback)
      {
        string returnUrl = Request.QueryString["Returnurl"];
        if (!String.IsNullOrEmpty(returnUrl))
        {
          url = returnUrl;
          if (Request.QueryString.Count > 1)
          {
            for (int i = 1; i < Request.QueryString.Count; i++)
            {
              url += "&" + Request.QueryString.GetKey(i) + "=" + Request.QueryString[i];
            }
          }
        }
      }
      txtUsername.Focus();
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
      DoLogin();
    }

    protected void btnUK_Click(object sender, ImageClickEventArgs e)
    {
      ((AdminBasePage)Page).CurrentLanguage = GlobalCache.Instance.English;
      Response.Redirect(Request.RawUrl);
    }

    protected void btnVN_Click(object sender, ImageClickEventArgs e)
    {
      ((AdminBasePage)Page).CurrentLanguage = GlobalCache.Instance.Vietnamese;
      Response.Redirect(Request.RawUrl);
    }

    private void DoLogin()
    {
      try
      {
        if (txtUsername.Text != "" && txtPass.Text != "")
        {
          User usr = new UserService().GetByUsername(txtUsername.Text);
          String inputPassword = Library.Encryption.MD5.Encrypt(txtPass.Text);
          if ((usr != null) && (usr.Password == inputPassword))
          {
            if (usr.Status == CommonStatus.Active)
            {
              ((AdminBasePage)Page).CurrentUser = usr;
              ((AdminBasePage)Page).CurrentUserPermission = new GroupPermissionService().GetByUserId(CurrentUser.Username);
              ((AdminBasePage)Page).CreateAuthenticationTicket(usr.Username);
              Response.Redirect(url);
            }
            else
              lblErrMsg.Text = Resources.Messages.ERR0053;
          }
          else
            lblErrMsg.Text = Resources.Messages.ERR0001;
        }
        else
        {
          lblErrMsg.Text = Resources.Messages.ERR0002;
        }
      }
      catch (Exception ex)
      {
        WriteLog("Login.aspx::DoLogin", ex);
      }
    }
  }
}
